import Device from '../models/device.js';
import { mockDevInfo, mockHealthData ,stopDataCollection,startDataCollection} from '../devices/mockDev.js';
import Result from '../utils/result.js';

export let deviceTimers = {};

export const intervalMap = {
  BPMonitor: 15,         // 血压计：每15分钟采集一次
  spO2Monitor: 10,       // 血氧仪：每10分钟采集一次
  BFPMonitor: 30,        // 体脂秤：每30分钟采集一次
  Thermometer: 15,       // 体温计：每15分钟采集一次
  BGMeter: 20,           // 血糖仪：每20分钟采集一次
  wearable: 5,           // 可穿戴设备：每5分钟采集一次（高频监测）
  ECGMonitor: 30,        // 心电图仪：每30分钟采集一次
  SleepMonitor: 45,      // 睡眠监测仪：每30分钟采集一次（可以及时捕捉到睡眠开始和结束）
  ActivityTracker: 5,    // 活动追踪器：每5分钟采集一次（活动数据需要更频繁）
  default: 60            // 默认值：每60分钟采集一次
};
export const setDeviceTimer = (timers) => {
    deviceTimers = timers;
}

export const pushDeviceTimer = (deviceId, timerId)=> {
    deviceTimers[deviceId] = timerId;
}

export const devlists = [
    'wearable',
    'BPMonitor',
    'BGMeter',
    'spO2Monitor',
    'ECGMonitor',
    'BFPMonitor',
    'Thermometer',
    'other',
];

const DeviceService = {
    async getDeviceList(userId) {
        try {
            // 通过userId查询设备列表
            const devices = await Device.findAll({
                where: {
                    userId: userId,
                },
            });
            return Result.success(devices,'获取设备列表成功');
        } catch (error) {
            throw error;
        }
    },
    async bindDevice(userId, deviceSN, type) {
        try {
            const device = await DeviceService.findBySN(deviceSN);
            if (device) {
                throw new Error('Device already exists!');
            }

            const deviceInfo = await mockDevInfo(type);
            
            if (!deviceInfo) {
                throw new Error('Device bind failed!');
            }

            deviceInfo.userId = userId;
            deviceInfo.sn = deviceSN;

            await Device.create(deviceInfo);
            
            return Result.success(deviceInfo,'成功绑定设备');
        } catch (error) {
            throw error;
        }
    },
    async makeAndBindDev(userId,type, metaData){
        try{
            const deviceInfo = await mockDevInfo(type);
            deviceInfo.userId = userId;
            deviceInfo.metaData = metaData;
            const device = await Device.create(deviceInfo); 


            const timerid = await startDataCollection(type, intervalMap[type], userId, device.id);

            deviceTimers[device.id]= timerid;

            return Result.success(device, 'Device bind successfully!');
        }catch(err){
            console.log(err)
            return Result.error(err.message);
        }

    },
    async unbindDevice(userId, deviceSN) {
        try {
            const device = await Device.findOne({
                where: {
                    userId: userId,
                    sn: deviceSN,
                },
            });
            if (!device) {
                throw new Error('Device not found!');
            }

            // 停止该设备的模拟数据生成定时器
            const timerId = deviceTimers[device.id];
            if (timerId) {
                stopDataCollection(timerId);
                delete deviceTimers[device.id];
                console.log(`Stopped data collection timer for device ID: ${device.id}`);
            }

            await device.destroy();

            return Result.success(deviceSN,'解绑设备成功');
        } catch (error) {
            throw error;
        }
    },
    async getDeviceStatus(deviceSN) {
        try {
            const device = await DeviceService.findBySN(deviceSN);
            if (!device) {
                throw new Error('Device not found!');
            }

            // 更新最后同步时间为当前时间
            device.lastSyncTime = new Date();
            
            if(device.status == 'inactive'){
                stopDataCollection(deviceTimers[device.id]);
            }

            // 保存设备状态更新
            await device.save();

            return  Result.success(device,'设备状态同步成功！');
        } catch (error) {
            console.log('updateDeviceStatusError:', error);
            throw error;
        }
    },

    async findBySN(deviceSN) {
        try {
            const device = await Device.findOne({
                where: {
                    sn: deviceSN,
                },
            });
            // console.log('findBySN:', device);

            return device;
        } catch (error) {
            throw error;
        }
    },
};

export default DeviceService;
